package fr.upmc.i3s.upmcontact.listeners;

import fr.upmc.i3s.upmcontact.R;
import fr.upmc.i3s.upmcontact.callbacks.IConnectivityChangeCallback;
import fr.upmc.i3s.upmcontact.tools.MobileDataUtils;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.widget.ImageView;
import android.widget.Toast;

public class OnConnectionChangeListener extends BroadcastReceiver {
	
	private ImageView ivConnectivity;
	private IConnectivityChangeCallback callback;
	private boolean isFirst;
	
	public OnConnectionChangeListener(ImageView ivConnectivity, IConnectivityChangeCallback callback) {
		super();
		this.ivConnectivity = ivConnectivity;
		this.callback = callback;
		this.isFirst = true;
	}

	@Override
	public void onReceive(Context ctx, Intent intent) {
		ConnectivityManager connectivityManager = (ConnectivityManager) ctx.getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo activeNetInfo = connectivityManager.getActiveNetworkInfo();
		if (activeNetInfo != null && activeNetInfo.getType() != MobileDataUtils.CONNECTIVITY_NONE) {
			if(!isFirst) {
				Toast.makeText(ctx, ctx.getString(R.string.online), Toast.LENGTH_SHORT).show();
			}
			if(callback != null) {
				callback.changed(true, activeNetInfo.getType());
			}
			ivConnectivity.setImageResource(R.drawable.ic_online_green);
			isFirst = false;
		} else {
			if(!isFirst) {
				Toast.makeText(ctx, ctx.getString(R.string.offline), Toast.LENGTH_SHORT).show();
			}
			if(callback != null) {
				callback.changed(false, MobileDataUtils.CONNECTIVITY_NONE);
			}
			ivConnectivity.setImageResource(R.drawable.ic_offline_red);
			isFirst = false;
		}
	}

}
